<?php 

define('TOEKN_PATH', './token.txt');

define('APPID', 'wxac466a2494571193');
define('APPSECRET', '21bf8a9b6bef75a9215831f35e1e24ff');


include_once './function.php';


/**
 * 获取访问授权
 */
class AccessToken
{
    /**
     * token的文件,从文件获取token,且未超期
     */
    static public function getToken()
    {
        $path = TOEKN_PATH;
        if (file_exists($path) && ((time()-filectime($path))<7200)) {
            $token = file_get_contents($path);
        } else {
            $token = static::refreshToken();
        }
        return $token;
    }

    /**
     * 刷新token
     */
    static public function refreshToken()
    {
        $api  = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
        $api .= '&appid='.APPID.'&secret='.APPSECRET;
        $token = post($api, null, false)['access_token'];
        if ($token) {
            file_put_contents(TOEKN_PATH, $token);
        }
        return $token;
    }
}

// var_dump(AccessToken::getToken());
